﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace GoodStuff.Silverlight
{
    public class SelectedItem<T> : ViewModelBase
    {
        public T DataItem { get; set; }
        private bool _isSelected;

        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                _isSelected = value;
                RaisePropertyChanged(() => IsSelected);
            }
        }
    }

    /// <summary>
    /// Helper class that allow you to select and unselect items
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SelectedItemsCollection<T> : ObservableCollection<SelectedItem<T>>
    {
        public SelectedItemsCollection()
        {

        }

        public SelectedItemsCollection(SelectedItemsCollection<T> source)
        {
            foreach (var x in source)
            {
                this.Add(x.DataItem, x.IsSelected);
            }
        }

        protected override void InsertItem(int index, SelectedItem<T> item)
        {
            item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
            base.InsertItem(index, item);
        }

        void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.OnCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
        }

        public void Add(T item, bool selected)
        {
            Add(new SelectedItem<T>() { DataItem = item, IsSelected = selected });
        }
        public void Add(T item)
        {
            Add(item, true);
        }

        public IEnumerable<T> SelectedItems
        {
            get
            {
                return this.Items.Where(p => p.IsSelected).Select(p => p.DataItem).ToList();
            }
            set
            {
                foreach (var item in this.Items)
                {
                    item.IsSelected = value.Contains(item.DataItem);
                }
            }
        }
    }
}
